package com.tuling.signalling.player.handler;

import com.tuling.signalling.MatchTools;
import com.tuling.signalling.websocket.handler.WebsocketServerHandler;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

import java.nio.charset.StandardCharsets;
public class PlayerHandler extends WebsocketServerHandler {


    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
        super.channelRead0(ctx, msg);
        if (MatchTools.streamerMapIdle.isEmpty()) {
            TextWebSocketFrame tws = new TextWebSocketFrame();
            tws.content().writeBytes("no streamer available".getBytes(StandardCharsets.UTF_8));
            ctx.channel().writeAndFlush(tws);
            ctx.channel().close();
        } else {
            MatchTools.matchFirst(ctx.channel().id().asLongText());
        }
    }

    @Override
    public void handlerTextWebSocketFrame(Channel channel, TextWebSocketFrame frame) {

    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        String id = channel.id().asLongText();
        MatchTools.addPlayer(id, channel);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        String id = channel.id().asLongText();
    }
}
